<template>
  <div class="login-page">
    <!-- <nut-button type="primary" @click="loginHandle">微信登录</nut-button> -->
    <button
      class="nut-button nut-button--primary nut-button--normal nut-button--round"
      open-type="getPhoneNumber"
      @getphonenumber="loginHandle"
      >微信登录</button
    >
    <nut-toast v-bind="toast" v-model:visible="toast.show" />
  </div>
</template>

<script lang="ts" setup>
import Taro from '@tarojs/taro'
import { login } from '@/api/login'
import { getStorage, saveAfterSuccessfulLogin } from '@/utils/storage'
import useToast from '@/hooks/useToast'
import useAuthShare from './hooks/useAuthShare'

let { toast, toastFail } = useToast()

const { isShare, toSharePage } = useAuthShare()

async function loginHandle({ detail }) {
  let { miniProgram } = Taro.getAccountInfoSync()

  try {
    let resData = await login(
      {
        appId: miniProgram.appId,
        // secret: '613eb2f69b7b7ddca8962477b66e3a59',
        openid: getStorage('openid'),
        iv: detail.iv,
        encryptedData: detail.encryptedData,
      },
      {
        fail(msg) {
          toastFail(msg)
        },
      },
    )
    saveAfterSuccessfulLogin(resData)

    if (isShare) {
      toSharePage()
    } else {
      Taro.switchTab({
        url: '/pages/index/index',
      })
    }
  } catch (e: any) {
    Taro.showToast({
      title: e.message,
    })
  }
}
</script>

<style lang="scss">
.login-page {
  padding: 100px 0;
  text-align: center;
}
</style>
